import { Plugin } from 'vue';
import axios, { AxiosResponse, Cancel } from 'axios';
import {store} from '@/store';
import router from '@/router';
import {ElMessage} from 'element-plus';

declare module 'axios' {
  interface AxiosResponse<T = any> {
    code: snumber;
    success: boolean;
    message: string;
  }

  interface AxiosRequestConfig {
    extra?: Record<string, any>;
  }
}

export default <Plugin>{
  install(app) {
    axios.defaults.timeout = 30000;
    import.meta.env.DEV?axios.defaults.baseURL = '/api':'';
    axios.interceptors.request.use((config) => {
      const token = store.state?.token ?? '';
      if (import.meta.env.DEV) config.withCredentials = true;
      if (token) config.headers!.Authorization = `Bearer ${token}`;
      return config;
    });
    axios.interceptors.response.use(
      (rsp) => {
        if (!rsp.config.url?.startsWith('/api')) {
          rsp.success = true;
          return rsp;
        }
        rsp.code = rsp.data?.code ?? 200;
        rsp.message = rsp.data?.message ?? rsp.statusText;
        rsp.success = rsp.code === 200;
        rsp.data = rsp.data?.data ?? rsp.data;

        return rsp;
      },
      (error: ErrorAxiosRsp) => {
        if (import.meta.env.DEV) {
          console.group('请求地址：' + error.response?.config?.url);
          console.error(error);
          console.log({ ...error });
          console.groupEnd();
        }
        const rsp = error.response || { message: '服务开小差了' };
        if (error.code === 'ECONNABORTED') {
          rsp.message = '';
          ElMessage.error('请求超时');
        }
        if (error instanceof axios.Cancel) {
          rsp.code = 'CANCELLED';
          rsp.message = error.message ?? '请求已取消';
        }
        rsp.success = false;
        if (rsp.status === 401) {
          rsp.message = '';
          setTimeout(() => {
            if (store.state.token) ElMessage.error('用户未登录或已失效，请重新登录');
            router.push('/logout');
          }, 0);
          // window.location.href = location.origin + '/logout';
        }
        if (rsp.status === 500) {
          ElMessage.error(rsp.data?.message || '服务异常，请稍候再试');
          rsp.message = '';
          // window.location.href = location.origin + '/logout';
        }
        return rsp;
      }
    );
  }
};

interface ErrorAxiosRsp {
  code: string;
  response: AxiosResponse;
}
